const app = getApp()

Page({
  data: {
    id: '',
    order: null,
    statusMap: {
      pending: {
        text: '待支付',
        color: '#ff4d4f'
      },
      paid: {
        text: '待发货',
        color: '#1890ff'
      },
      shipped: {
        text: '已发货',
        color: '#52c41a'
      },
      completed: {
        text: '已完成',
        color: '#666666'
      },
      cancelled: {
        text: '已取消',
        color: '#999999'
      }
    }
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadOrder(options.id)
    }
  },

  // 加载订单详情
  async loadOrder(id) {
    // 显示加载动画
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    try {
      const db = wx.cloud.database()
      const res = await db.collection('orders').doc(id).get()
      const orderData = res.data

      // 处理时间格式
      if (orderData.createTime) {
        // 如果是Date对象，转换为时间戳
        orderData.createTime = {
          $date: new Date(orderData.createTime).getTime()
        };
      }
      
      this.setData({ 
        order: orderData,
        statusInfo: this.data.statusMap[orderData.status]
      })
    } catch (error) {
      console.error('加载订单详情失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      // 隐藏加载动画
      wx.hideLoading()
    }
  },

  // 取消订单
  async cancelOrder() {
    try {
      const { confirm, content } = await wx.showModal({
        title: '取消订单',
        content: '确定要取消这个订单吗？',
        confirmText: '确定取消',
        confirmColor: '#ff4d4f'
      })
      
      if (confirm) {
        wx.showLoading({
          title: '处理中...',
          mask: true
        });

        const db = wx.cloud.database()
        await db.collection('orders').doc(this.data.id).update({
          data: {
            status: 'cancelled',
            statusDesc: '已取消',
            cancelReason: content || '用户取消',
            updateTime: db.serverDate(),
            timeline: db.command.push({
              status: 'cancelled',
              statusDesc: '订单取消',
              time: db.serverDate()
            })
          }
        })
        
        wx.showToast({
          title: '已取消订单',
          icon: 'success'
        })
        
        this.loadOrder(this.data.id)
      }
    } catch (error) {
      console.error('取消订单失败：', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 支付订单
  async payOrder() {
    try {
      wx.showLoading({
        title: '发起支付...',
        mask: true
      });

      const res = await wx.cloud.callFunction({
        name: 'pay',
        data: {
          orderId: this.data.id,
          totalFee: this.data.order.totalAmount * 100
        }
      });

      if (res.result && res.result.payment) {
        wx.requestPayment({
          ...res.result.payment,
          success: () => {
            const db = wx.cloud.database()
            db.collection('orders').doc(this.data.id).update({
              data: {
                status: 'paid',
                statusDesc: '待发货',
                payStatus: 'paid',
                updateTime: db.serverDate(),
                timeline: db.command.push({
                  status: 'paid',
                  statusDesc: '支付完成',
                  time: db.serverDate()
                })
              }
            });
            
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            });

            this.loadOrder(this.data.id)
          },
          fail: (err) => {
            console.error('支付失败：', err)
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        });
      }
    } catch (error) {
      console.error('发起支付失败：', error)
      wx.showToast({
        title: '支付失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 复制订单号
  copyOrderNo() {
    wx.setClipboardData({
      data: this.data.order.orderNo,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        })
      }
    })
  }
}) 